package filewriting;

import guiobjects.Observation;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;

import commonfunctions.Functions;
import commonfunctions.Matrix;


/**
 * Creates a display of the graph for when the IDs aren't known. Displays the entire track, except
 * for single-point tracks.
 * 
 * @author Trevor Terris
 *
 */
public class SimpleViewWriter 
{
	public static final String SIMPLE_VIEW_NAME = "simple-view.txt";
	
	public static Thread startWriting(ArrayList<Observation> obs, Matrix weights, Matrix tracks, String dir)
	{
		Thread toReturn = new WritingThread(obs, weights, tracks, dir);
		toReturn.start();
		return toReturn;
	}
	
	private static class WritingThread extends Thread
	{
		private ArrayList<Observation> myObservations;
		private Matrix myWeights;
		private Matrix myTracks;
		private String myDirName;
		public WritingThread(ArrayList<Observation> obs, Matrix weights, Matrix tracks, String dir)
		{
			myObservations = obs;
			myWeights = weights;
			myTracks = tracks;
			myDirName = dir;
		}
		public void run()
		{
			try
			{
				int lastFrame = myObservations.get(myObservations.size() - 1).frameNum;
				int[] pathItsOn = new int[myObservations.size()];
				ArrayList<Integer> starts = Functions.trackStarts(myTracks);
				int numRemoved = 0;
				for (int i = 0; i < starts.size(); i++)
				{
					if (i >= starts.size())
						break;
					boolean hasNext = false;
					for (int j = starts.get(i); j < myObservations.size(); j++)
					{
						if (myTracks.getBoolean(starts.get(i), j))
						{
							hasNext = true;
						}
					}
					if(!hasNext)
					{
						starts.remove(i);
						numRemoved++;
						i--;
					}
				}
				File f = new File(myDirName + "/" + SIMPLE_VIEW_NAME);
		        Writer output = null;
		        output = new BufferedWriter(new FileWriter(f));
		        output.flush();
		        for (int i = 0; i < myTracks.length(); i++)
		        {
		        	for(int j = i + 1; j < myTracks.length(); j++)
		        	{
		        		if (myTracks.getBoolean(i, j))
		        		{
		        			int y = (starts.contains(i))?starts.indexOf(i):pathItsOn[i];
		        			pathItsOn[j] = y;
		        			double yVal = 0.01 + 0.98 * ((double)y)/((double)starts.size());
		        			double xStart = 0.05 + 0.90 * (double)myObservations.get(i).frameNum / (double)lastFrame;
		        			double xEnd = 0.05 + 0.90 * (double)myObservations.get(j).frameNum / (double)lastFrame;
							int width = (int)(myWeights.get(i, j) / 0.2) + 1;
		        			
		        			String toWrite = "Line 1 " + xStart + " " + yVal + " " + xEnd + " " + yVal + " 0 0 0 " + width + "\n";
		        			output.write(toWrite);
		        			break;
		        		}
		        	}
		        }
		        output.write("Text 1 0.0 1.0 Single-Point tracks: " + numRemoved);
		        output.close();
			}
			catch (Exception e)
			{
				System.out.println("Error.");
			}
		}
	}
}
